package com.yurun.filemodule.controller;

import com.yurun.commonapi.api.CommonResult;
import com.yurun.filemodule.service.FileUploadService;
import com.yurun.filemodule.utils.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/fileManage")
@Api(value = "文件上传下载模块", tags = "文件")
public class FileUploadController {

    private static final Logger log = LoggerFactory.getLogger(FileUploadController.class);

    // 注入配置中图片保存路径
    @Value("${user.filepath}")
    private String filePath;

    @Autowired
    private FileUploadService fileUploadService;

    @Autowired
    public void setFileUploadService(FileUploadService fileUploadService) {
        this.fileUploadService = fileUploadService;
    }

    @RequestMapping("/fileSize")
    @ApiOperation("获取文件总数")
    public Integer fileSize(){
        return fileUploadService.fileSize();
    }

    //使用默认路径
    @PostMapping(value = "/upload")
    @ApiOperation("上传文件")
    public CommonResult upload(MultipartFile file, HttpServletRequest req) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        Map<String, Object> result = new HashMap<>();
        String format = sdf.format(new Date());
        String realPath = filePath ;//this.getClass().getClassLoader().getResource("static").getFile();//req.getServletContext().getRealPath("/") + format;
        System.out.println(realPath);
        File folder = new File(realPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
        System.out.println(newName);
        try {
            file.transferTo(new File(folder, newName));
            String url = realPath + newName;
            result.put("status", "OK");
            result.put("name", newName);
            result.put("url", "http://120.79.186.60:8887/file/image/" + newName);
        } catch (IOException e) {
            result.put("status", "ERROR");
            result.put("msg", e.getMessage());
        }
        return CommonResult.success(result);
    }

    //下载
    @GetMapping("/download/{id}")
    @ApiOperation("文件下载")
    public AjaxResult downloadFile(HttpServletResponse response, @PathVariable("id") Integer id) throws IOException {
        try{
            fileUploadService.download(response, id);
        }catch(Exception e){
            return AjaxResult.error("文件下载失败");
        }
        return AjaxResult.success("文件下载成功");
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation("文件删除")
    public AjaxResult delete(@PathVariable("id") Integer id){
        return AjaxResult.success("删除成功",fileUploadService.deleteById(id));
    }

    @PutMapping("/delete/status/{id}")
    @ApiOperation("文件更新ifExist")
    public AjaxResult deleteStatus(@PathVariable("id") Integer id){
        return AjaxResult.success("更新ifExist成功",fileUploadService.deleteStatus(id));
    }
}
